package com.qianxp.designparttern.observe;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author qianxp
 * @createTime 2019/11/20 0020
 */
public abstract class Subject {
    private List<Class> classList = new ArrayList<>();

    public Subject(){
        try {
            this.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void awake(){
         classList.stream().map(clazz -> {
             try {
                 return (Observe) clazz.newInstance();
             } catch (Exception e) {
                 e.printStackTrace();
             }
             return null;
         }).filter(Objects::nonNull).forEach(Observe::awake);
    }

    public void init() throws Exception {
        Enumeration<URL> enums = Thread.currentThread().getContextClassLoader().getResources(this.getClass().getPackage().getName().replace(".", File.separator));
        while (enums.hasMoreElements()){
            URL url = enums.nextElement();
            String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
            File dir = new File(filePath);
            Arrays.stream(Objects.requireNonNull(dir.listFiles())).forEach(file -> {
                try {
                    Class clazz = Class.forName(TestMain.class.getPackage().getName() + "."+file.getName().replace(".class",""));
                    Optional optional = Arrays.stream(clazz.getInterfaces()).filter(inter-> inter.equals(Observe.class)).findAny();
                    if(optional.isPresent()){
                        classList.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            });
        }
    }

}
